﻿using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace bonus.Controllers
{
	public class RegisterController : Controller
	{
		/// <summary>
		/// 注册
		/// </summary>
		/// <returns></returns>
		public ActionResult Index()
		{
			return View();
		}


		/// <summary>
		/// 注册用户(管理员)
		/// </summary>
		/// <returns></returns>
		public ActionResult AddUser()
		{

			Repository.Repository tool = new Repository.Repository();

			var filter = Builders<Models.User>.Filter.Where(p => p.UserType == Models.User.TypeClass.COMPANY || p.UserType == Models.User.TypeClass.CONTENT);

			var list = tool.GetMany(filter);

			return View(list);
		}


		/// <summary>
		/// 开通账号申请页面
		/// </summary>
		/// <returns></returns>
		public ActionResult SetUpAnAccount()
		{
			return View();
		}

		/// <summary>
		/// 开通账号申请JSON返回数据
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		public JsonResult Account()
		{
			Repository.Repository tool = new Repository.Repository();

			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());

			if (user == null || user.UserType != Models.User.TypeClass.ADMIN)
			{
				return Json(new { Code = "FAIL", Msg = "用户权限不够或未登陆" });
			}

			var filter = Builders<Models.Message>.Filter.Where(p => string.IsNullOrEmpty(p.Content));

			var list = tool.GetMany(filter);

			if (list == null)
			{
				list = new List<Models.Message>();
			}

			return Json(new { Code = "OK", Msg = "查询成功", Data = list, total = list.Count });
		}

		/// <summary>
		/// 回复申请账户
		/// </summary>
		/// <param name="id">消息标识</param>
		/// <param name="content">回复内容</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult ResultMsg(string id, string content)
		{
			Repository.Repository tool = new Repository.Repository();

			var entity = tool.GetOne<Models.Message>(id);

			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "消息不存在" });
			}

			var update = Builders<Models.Message>.Update.Set("Content", content);

			var result = tool.UpdateOne<Models.Message>(id, update);

			return Json(new { Code = "OK", Msg = "已回复" });
		}

		/// <summary>
		/// 增加用户
		/// </summary>
		/// <param name="mUP">金钱上级</param>
		/// <param name="eUP">经验上级</param>
		/// <param name="type">用户类型</param>
		/// <param name="content">所属服务中心或公司</param>
		/// <param name="name">用户名称</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult Indexs(string mUP, string eUP, string content, string userName, string mobile, int type)
		{
			Repository.Repository tool = new Repository.Repository();

			if (!string.IsNullOrEmpty(mUP))
			{
				var filter = Builders<Models.User>.Filter.Eq("NO", mUP);

				var entity = tool.GetOne(filter);

				if (entity == null)
				{
					return Json(new { Code = "FAIL", Msg = "上级用户不存在" });
				}

				if (type == Models.User.TypeClass.User && entity.UserType != Models.User.TypeClass.User)
				{
					return Json(new { Code = "FAIL", Msg = "用户上级用户不能是服务商或公司" });
				}

			}

			if (!string.IsNullOrEmpty(eUP))
			{
				var filter = Builders<Models.User>.Filter.Eq("NO", eUP);

				var entity = tool.GetOne(filter);

				if (entity == null)
				{
					return Json(new { Code = "FAIL", Msg = "上级用户不存在" });
				}
				if (entity.UserType != Models.User.TypeClass.User)
				{
					return Json(new { Code = "FAIL", Msg = "上级用户不能是服务商或公司" });
				}
			}

			if (!string.IsNullOrEmpty(content))
			{
				var filter = Builders<Models.User>.Filter.Eq("NO", content);

				var entity = tool.GetOne(filter);

				if (entity == null)
				{
					return Json(new { Code = "FAIL", Msg = "服务中心或公司不存在" });
				}
			}

			Models.User user = new Models.User();
			user.AddDT = DateTime.Now;
			user.EUP = eUP;
			user.EXP = "0";
			user.Name = userName;
            user.Mobile = mobile;
			user.UserType = type;
			user.Cantent = content;
			if (type != Models.User.TypeClass.User)
			{
				user.Level = Models.User.LevelClass.OTHER;
			}
			else
			{
				user.Level = Models.User.LevelClass.STUDENT;
			}

			user.Money = 0;
			user.MUP = mUP;
			var no = "";
			Models.User isUser = null;
			do
			{
				no = "SY" + getNo();

				if (type == Models.User.TypeClass.COMPANY)
				{
					Random ran = new Random();
					int RandKey = ran.Next(1000, 9999);

					no = "CM" + RandKey.ToString();
				}
				else if (type == Models.User.TypeClass.CONTENT)
				{
					Random ran = new Random();
					int RandKey = ran.Next(10000, 99999);

					no = "CO" + RandKey.ToString();
				}

				var filter = Builders<Models.User>.Filter.Eq("NO", no);
				isUser = tool.GetOne(filter);
			} while (isUser != null);

			user.NO = no;

			string pwd1 = GetRandomString(6);

			user.Pwd1 = Repository.FuBeiMD5.Sign(pwd1, Models.WebConfig.KEY, Models.WebConfig.UFT8);
			user.Pwd2 = user.Pwd1;
			user._id = ObjectId.GenerateNewId();
			var result = tool.AddOneAsync(user);
			return Json(new { Code = "OK", Msg = "成功", Account = user.NO, PWD1 = pwd1 });

		}


		///<summary>
		///生成随机字符串 
		///</summary>
		///<param name="length">目标字符串的长度</param>
		///<param name="custom">要包含的自定义字符，直接输入要包含的字符列表</param>
		///<returns>指定长度的随机字符串</returns>
		public static string GetRandomString(int length)
		{
			byte[] b = new byte[4];
			new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
			Random r = new Random(BitConverter.ToInt32(b, 0));
			string s = null, str = "";
			str += "0123456789";
			//str += "abcdefghijklmnopqrstuvwxyz";
			//str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			//str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
			for (int i = 0; i < length; i++)
			{
				s += str.Substring(r.Next(0, str.Length - 1), 1);
			}
			return s;
		}

		/// <summary>
		/// 生成水随机数
		/// </summary>
		/// <returns></returns>
		public static string getNo()
		{
			//byte[] buffer = Guid.NewGuid().ToByteArray();
			//return BitConverter.ToUInt32(buffer, 8).ToString();
			Random ran = new Random();
			int RandKey = ran.Next(100000, 999999);

			return RandKey.ToString();
		}


		/// <summary>
		/// 增加用户
		/// </summary>
		/// <param name="mUP">金钱上级</param>
		/// <param name="eUP">经验上级</param>
		/// <param name="type">用户类型</param>
		/// <param name="content">所属服务中心或公司</param>
		/// <param name="name">用户名称</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult Index(string mId)
		{

			if (string.IsNullOrEmpty(mId))
			{
				return Json(new { Code = "FAIL", Msg = "请重试" });
			}

			Repository.Repository tool = new Repository.Repository();

			var message = tool.GetOne<Models.Message>(mId);
			if (message == null)
			{
				return Json(new { Code = "FAIL", Msg = "消息不存在" });
			}

			if (!string.IsNullOrEmpty(message.MUP))
			{
				var filter = Builders<Models.User>.Filter.Eq("NO", message.MUP);

				var entity = tool.GetOne(filter);

				if (entity == null)
				{
					return Json(new { Code = "FAIL", Msg = "上级用户不存在" });
				}

				if (entity.UserType != Models.User.TypeClass.User)
				{
					return Json(new { Code = "FAIL", Msg = "用户上级用户不能是服务商或公司" });
				}

			}

			if (!string.IsNullOrEmpty(message.EUP))
			{
				var filter = Builders<Models.User>.Filter.Eq("NO", message.EUP);

				var entity = tool.GetOne(filter);

				if (entity == null)
				{
					return Json(new { Code = "FAIL", Msg = "上级用户不存在" });
				}
				if (entity.UserType != Models.User.TypeClass.User)
				{
					return Json(new { Code = "FAIL", Msg = "上级用户不能是服务商或公司" });
				}
			}

			if (!string.IsNullOrEmpty(message.Contre))
			{
				var filter = Builders<Models.User>.Filter.Eq("NO", message.Contre);

				var entity = tool.GetOne(filter);

				if (entity == null)
				{
					return Json(new { Code = "FAIL", Msg = "服务中心或公司不存在" });
				}
			}

			Models.User user = new Models.User();
			user.AddDT = DateTime.Now;
			user.EUP = message.EUP;
			user.EXP = "0";
			user.Name = message.UserName;
			user.UserType = Models.User.TypeClass.User;
			user.Cantent = message.Contre;

			user.Level = Models.User.LevelClass.OTHER;

			user.Money = 0;
			user.MUP = message.MUP;
			var no = "";
			Models.User isUser = null;
			do
			{
				no = "SY" + getNo();
				var filter = Builders<Models.User>.Filter.Eq("NO", no);
				isUser = tool.GetOne(filter);
			} while (isUser != null);

			user.NO = no;

			string pwd1 = GetRandomString(6);

			user.Pwd1 = Repository.FuBeiMD5.Sign(pwd1, Models.WebConfig.KEY, Models.WebConfig.UFT8);
			user.Pwd2 = user.Pwd1;
			user._id = ObjectId.GenerateNewId();
			var result = tool.AddOneAsync(user);

			message.Content = "账户:" + user.NO + " 一级密码和二级密码:" + pwd1;

			var updatau = Builders<Models.Message>.Update.Set("Content", "账户:" + user.NO + " 一级密码和二级密码:" + pwd1);

			var resultu = tool.UpdateOne(message._id.ToString(), updatau);

			return Json(new { Code = "OK", Msg = "回复成功" });

		}


	}
}